import seabot
from aiocqhttp.exceptions import Error as CQHttpError
from seasun.plugins.weather.tuling import *
import seasun.datasoures.user_config as uconfig
from seasun.datasoures.xiaohua_config import selectfirst, updatexiaohua_status
from .config import text, url, apikey
import datetime
from .log import logger
from .date2time import date2time


bot = seabot.get_bot()

@seabot.scheduler.scheduled_job('cron', hour=0, minute=0, second=0,  start_date='2019-8-1 00:20:00')
def update() -> None:
    '''
    每天零点更新数据
    :return:
    '''

    # 获取当天日期
    month = datetime.datetime.now().strftime('%Y-%m')
    today = datetime.datetime.now()
    logger(month, '\n'+today.strftime('%Y-%m-%d'))

    # 获取笑话
    xiaohua = selectfirst()
    title = '每日开心一笑！(*^_^*)   ——>' + xiaohua.title
    xtext = xiaohua.text
    id = xiaohua.id
    # 获取发送天气或者笑话的配置
    list = uconfig.find_weather()
    for li in list:
        qq = li.qq
        if(li.wstatus == 1):
            wtime = li.wtime
            text = li.text
            address = li.address + "天气"
            # 配置天气定时任务
            seabot.scheduler.add_job(weather, 'date', run_date=date2time(today, wtime), args=[month, text, qq, address])

        if(li.xstatus == 1):
            xtime = li.xtime
            # 配置笑话定时任务
            seabot.scheduler.add_job(send, 'date', run_date=date2time(today, xtime), args=[title+'\n'+xtext, qq])
            updatexiaohua_status(id)
            logger(month, qq+'  ' + id)

# 从图灵api获取天气信息
async def weather(month: str, text: str, qq: str, address: str) -> None:

    data = await tuling_weather(address, url, apikey)
    await send(text+"\n"+data, qq)
    logger(month, qq + '   ' + data)
# 调用酷q发送信息接口
async def send(data:str, qq:str):

    try:
        # await bot.send_group_msg(group_id=631074573, message=data)
        await bot.send_private_msg(user_id=qq, message=data)
    except CQHttpError:
        pass